<?php

namespace app\common\business;

use think\Exception;

class Category
{

    public $categoryObj = null;

    public function __construct()
    {
        $this->categoryObj = new \app\common\model\mysql\Category();
    }

    //新增分类
    public function add($data)
    {
        $data['status'] = 1;
        $name = $data['name'];
        //根据 $name 去数据库查询是否存在这条记录
        $name = $this->categoryObj->where('name', $name)->find();
        //  dump($name);exit();

        if (!empty($name)) {
            throw new Exception('分类名已存在');
        }

        try {
            $this->categoryObj->save($data);
        } catch (\Exception $e) {
            throw new Exception("服务内部异常");
        }
        return $this->categoryObj->id;

    }

    //编辑逻辑
    public function update($data)
    {
        $name = $data['name'];
        $id = $data['id'];
        //根据 $name 去数据库查询是否存在这条记录
        $name = $this->categoryObj->where('name', $name)->find();
        if (!empty($name)) {
            throw new Exception('分类名已存在');
        }
        try {
            $res = $this->categoryObj->updateById($id, $data);
        } catch (\Exception $e) {
            return false;
        }

        return $res;
        //return $this->categoryObj->id;

    }

    //查询所有分类
    public function getNormalCategorys()
    {

        $field = "id,name,pid";
        $categorys = $this->categoryObj->getNormalCategorys($field);

        if (!$categorys) {
            return $categorys;
        }
        $categorys = $categorys->toArray();

        return $categorys;
    }

    //查询所有分类 将id改为category_id
    public function getNormalAllCategorys()
    {

        $field = "id as category_id,name,pid";
        $categorys = $this->categoryObj->getNormalCategorys($field);

        if (!$categorys) {
            return $categorys;
        }
        $categorys = $categorys->toArray();

        return $categorys;
    }

    //获取分页
    public function getLists($data, $num)
    {
        $list = $this->categoryObj->getLists($data, $num);
        //  halt($list->render());
        if (!$list) {
            return [];
        }
        $result = $list->toArray();
        $result['render'] = $list->render();

        //查出所有一级分类的id
        $pids = array_column($result['data'], 'id');
        //获取当前id的PID下面子栏目的数量
        if ($pids) {
            $idCountResult = $this->categoryObj->getChildCountInPids(['pid' => $pids]);

            $idCountResult = $idCountResult->toArray();
            //halt($idCountResult);
            $idCounts = [];
            foreach ($idCountResult as $countResult) {
                $idCounts[$countResult['pid']] = $countResult['count'];
            }
        }

        //赋值
        if ($result['data']) {
            foreach ($result['data'] as $k => $value) {

                $result['data'][$k]['childCount'] = $idCounts[$value['id']] ?? 0;
            }
            // halt($result['data']);
        }


        return $result;
    }

    //根据ID获取这条记录
    public function getById($id)
    {
        $result = $this->categoryObj->find($id);
        if (empty($result)) {
            return [];
        }
        $result = $result->toArray();
        return $result;
    }

    //排序
    public function listorder($id, $listorder)
    {
        //查询 id这条数据是否存在
        $res = $this->getById($id);
        if (!$res) {
            throw new Exception("不存在该条记录");
        }
        $data = [
            'listorder' => $listorder
        ];

        try {
            $res = $this->categoryObj->updateById($id, $data);
        } catch (\Exception $e) {
            return false;
        }
        return $res;

    }

    //更新状态的逻辑
    public function status($id, $status)
    {
        //查询 id是否存在
        $res = $this->getById($id);
        if (!$res) {
            throw new Exception('不存在该条记录');
        }
        if ($res['status'] == $status) {
            throw new Exception('状态修改前和修改后一样没有意义');
        }
        $data = [
            "status" => intval($status),
        ];
        try {
            $res = $this->categoryObj->updateById($id, $data);
        } catch (\Exception $e) {
            //记录日志
            return false;
        }
        return $res;

    }

    /**
     * 获取本级分类内容
     *
     * @param int $pid 传PID获取本级所有  传ID获取下级
     * @param string $field
     * @return array|\think\Collection
     */
    public function getNormalByPid($pid = 0, $field = "id,name,pid")
    {
        try {
            $res = $this->categoryObj->getNormalByPid($pid, $field);
        } catch (\Exception $e) {
            //日志
            return [];
        }
        $res = $res->toArray();

        return $res;
    }

    //商品列表页 按栏目检索的内容
    //！修改 不展示三级分类
    public function search($cid)
    {
        //获取当前ID的数据
        $res = $this->getById($cid);
        if (!$res) {
            return [];
        }
        $result = [];
        //根据数据查询分类
        $field = "id,name";
        //如果PID是0就是一级分类
        if (empty($res['pid'])) {
            //获取二级分类数据
            $categoryOne = $this->categoryObj->getNormalByPid($res['id'], $field);
            $categoryOne = $categoryOne->toArray();
            //如果没有二级分类 就返回空
            if (empty($categoryOne)) {

                $categoryOne = [];
                $categoryOneId = [];
            } else {
                $categoryOneId = $categoryOne[0]['id'];
            }
            //获取三级分类
            try {
                $categoryTow = $this->categoryObj->getNormalByPid($categoryOneId, $field);
            } catch (\Exception $e) {
                return [];
            }
            $categoryTow = $categoryTow->toArray();
            //如果没有三级分类 就返回空
            if (empty($categoryTow)) {
                $categoryTow = [];
                $categoryTowId = [];
            } else {
                $categoryTowId = $categoryTow[0]['id'];
            }
            //组装数据
            $result = [
                'name' => $res['name'],
                "focus_ids" => [$categoryOneId, $categoryTowId],
                "list" => [$categoryOne, $categoryTow],
            ];


            //  dump($result);exit();
            return $result;

        } else {

            //点击二级或三级分类的时候  获取上级分类
            //根据categoryid 获取上级分类
            $result = [];
            //获取当前ID的数据
            $res = $this->getById($cid);
            if (!$res) {
                return [];
            }
            $categoryOneId = $res['id'];
            $pid = intval($res['pid']);
            //获取一级分类数据
            $categorys = $this->getById($pid);
            //如果为0 上一级就是一级分类 点击的就是二级分类
            if (empty($categorys['pid'])) {
                //获取二级分类所有数据
                $categoryOneName = $res['name'];
                $categoryOne = [
                    "id" => $categoryOneId,
                    "name" => $categoryOneName,
                ];
                //获取三级分类
                try {
                    $categoryTow = $this->categoryObj->getNormalByPid($categoryOneId, $field);
                } catch (\Exception $e) {
                    return [];
                }
                $categoryTow = $categoryTow->toArray();
                //如果没有三级分类 就返回空
                if (empty($categoryTow)) {
                    $categoryTow = [];
                    $categoryTowId = [];
                } else {
                    $categoryTowId = $categoryTow[0]['id'];
                }

                $result = [
                    'name' => $categorys['name'],
                    "focus_ids" => [$categoryOneId, $categoryTowId],
                    "list" => [[$categoryOne], $categoryTow],
                ];
                return $result;
            } else {
                //获取三级分类数据
                $res = $this->getById($cid);
                if (!$res) {
                    return [];
                }
                $categoryTowId = $res['id'];
                $categoryTowName = $res['name'];
                $categoryTow = [
                    "id" => $categoryTowId,
                    "name" => $categoryTowName,
                ];
                //获取二级分类数据

                $categoryTowPid = $res['pid'];
                $categoryOne = $this->categoryObj->getNormalById($categoryTowPid, $field);
                $categoryOne = $categoryOne->toArray();
                $categoryOneRes = $this->getById($categoryOne[0]['id']);
                //获取一级分类
                $categoryOnePid = $categoryOneRes['pid'];
                $category = $this->categoryObj->getNormalById($categoryOnePid, $field);
                $categorys = $category->toArray();

                $result = [
                    'name' => $categorys[0]['name'],
                    "focus_ids" => [$categoryOne[0]['id'], $categoryTowId],
                    "list" => [$categoryOne, [$categoryTow]]
                ];
                return $result;
            }
        }
    }

    //根据二级分类获取三级分类
    public function sub($id)
    {
        //获取当前ID的数据
        $res = $this->getById($id);
        if (!$res) {
            return [];
        }

        //根据数据查询分类
        $field = "id,name";
         $category =$this->getNormalByPid($id,$field);
       $result= $category;
       // dump($category);exit();
       return $result;

    }


}